%%Test5:
% Loads a gallery of related images and selects one in a uniform fashion
% which is then showed together with 2*aperture surrounding images.

%Screen('Preference', 'SkipSyncTests', 1); %this is to work in LABS computer

%initial params
screenNum=0;
res=[640 480];
clrdepth=32;
[wPtr, rect]=Screen('OpenWindow', screenNum, 0, [0 0 res(1) res(2)], clrdepth);

white=WhiteIndex(wPtr);
Screen('FillRect', wPtr, white);

%compute monitor's refresh rate
refresh = Screen('GetFlipInterval', wPtr);
vbl = Screen('Flip', wPtr);

%image gallery parameters:
folder = 'faces/Stimuli/6_happy/nr_all_hap_';
fileExt = '.jpg';
qtyFaces = 30;
aperture = 5;

descending = true;
%descending = mod(round(unifrnd(1,10)),2) == 0;

%stimulus setup
tpp = 0.050; %time per picture
qtyFrames = tpp/refresh; %qty of frames per picture based on monitor's refresh rate.

gallery = cell(1,qtyFaces);

try
    for i=1:qtyFaces
        file = strcat(folder, num2str(i),fileExt);
        
        gallery{i} = Screen('MakeTexture', wPtr, imread(file));
    end
catch er
    error('Error while loading images!!');
end

%select random pivot (integer between [1+aperture, qtyFaces-aperture]
pivot = round(unifrnd(1+aperture, qtyFaces-aperture));

for k=1:10
    aperture=round(unifrnd(1,7));
    pivot = round(unifrnd(1+aperture, qtyFaces-aperture));
    descending=mod(round(unifrnd(1,10)),2) == 0;
    
    if(descending)
        for i=1:2*aperture
            j = pivot + aperture - i;
            Screen('DrawTexture', wPtr, gallery{j});
            vbl  = Screen('Flip', wPtr, vbl + refresh * (qtyFrames - 0.4) );
        end
    else
        for i=1:2*aperture
            j = pivot - aperture + i;
            Screen('DrawTexture', wPtr, gallery{j});
            vbl  = Screen('Flip', wPtr, vbl + refresh * (qtyFrames - 0.4));
        end

    end
    
end
        







Screen('CloseAll');
ShowCursor;


